package com.yhsoft.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpClient {
    public static void main(String[] args) throws Exception {
        JSONObject data = new JSONObject();
        data.put("pageNum", 1);
        data.put("pageSize", 10);
        String param = data.toString();
        Object o = requestPostUrl("http://testopenapi.fsiling.com/api/partner/balance", param);
        System.out.println("结果：" + o.toString());
    }

    /**
     * 调用接口
     *
     * @param url
     * @param parameter
     * @return
     * @throws Exception
     */
    public static Object requestPostUrl(String url, String parameter) throws Exception {

        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");

        // 设置请求的参数
        StringEntity stringEntity = new StringEntity(parameter, "utf-8");

        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();

        httpPost.setConfig(config);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                res.append(body);
            }
        }
        Object jsonMap = JSON.parse(res.toString());
        return jsonMap;

    }
}